String text = "line 1\n\nline 3\n\n\nline 5"; String adjusted = text.replaceAll("(?m)^[ \t]*\r?\n", ""); // ...